let signaturePad = null
let dataURL = DEFAULT_DATA_URL

/**
 * 调整 canvas 的大小
 */
function resizeCanvas() {
  const canvas = document.getElementById('canvas')
  const ratio = Math.max(window.devicePixelRatio || 1, 1)
  canvas.width = canvas.offsetWidth * ratio
  canvas.height = canvas.offsetHeight * ratio
  const context = canvas.getContext('2d')
  context.scale(ratio, ratio)
}

/* function drawSomething() {
  const canvas = document.getElementById('canvas')
  const context = canvas.getContext('2d')
  context.fillStyle = 'rgb(17, 119, 255)'
  context.fillRect(0, 0, 100, 100)
}

drawSomething() */


/**
 * 根据图片的 Base64 编码，把内容显示到签名板上
 */
function redisplay() {
  signaturePad && dataURL && signaturePad.fromDataURL(dataURL)
}

/**
 * 清除签名板内容
 */
function clear() {
  signaturePad.clear()
  dataURL = null
}

/**
 * 获取签名板内容（图片的 Base64 编码）
 */
function save() {
  if (signaturePad.isEmpty()) return console.log('请签名')
  dataURL = signaturePad.toDataURL()
  console.log(dataURL)

  const blob = base64ToBlob(dataURL)
  console.log(blob)

  const file = blobToFile(blob, '图片.png')
  console.log(file)

  // 把 File 显示到 img 元素上
  /* const img = document.getElementById('img')
  img.src = window.URL.createObjectURL(file) */
}

resizeCanvas()

const canvas = document.getElementById('canvas')
// 创建 SignaturePad
const options = { penColor: "rgb(66, 133, 244)" }
signaturePad = new SignaturePad(canvas, options)

document.getElementById('redisplay').addEventListener('click', redisplay)
document.getElementById('clear').addEventListener('click', clear)
document.getElementById('save').addEventListener('click', save)

window.addEventListener('resize', () => {
  resizeCanvas()
  // 回显
  redisplay()
})